import React from 'react';
import produce from 'immer';
import { getToken } from '@/zero/utils/token';
import PdfViewer from '../PdfViewer';
import XmlViewer from '../XmlViewer';
import ExcelViewer from '../ExcelViewer';
import DocxViewer from '../DocxViewer';

const Index = (props) => {
  const {
    src,
    value,
    onLine = window.navigator.onLine,
    width = '100%',
    height = 'calc(100vh - 155px)',
    style,
    pdf,
    ...rest
  } = props;

  const newSrc = produce(src || value, (draftState) => {
    if (draftState) {
      if (!draftState.includes('?')) {
        draftState = `${draftState}?token=${getToken()}`;
      }
      if (/\.(doc|xls|ppt|dot)x?($|\?|#)/i.test(draftState) && onLine) {
        draftState = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
          draftState,
        )}`;
      }
    }
    return draftState;
  });

  if (/\.pdf($|\?|#)/i.test(newSrc) && newSrc.startsWith(window.location.origin)) {
    return <PdfViewer src={newSrc} {...pdf} {...rest} />;
  }

  if (/\.xml($|\?|#)/i.test(newSrc)) {
    return <XmlViewer src={newSrc} {...rest} />;
  }

  if (!onLine) {
    if (/\.(xls)x?($|\?|#)/i.test(newSrc)) {
      return <ExcelViewer src={newSrc} {...rest} />;
    }
    if (/\.docx($|\?|#)/i.test(newSrc)) {
      return <DocxViewer src={newSrc} {...rest} />;
    }
  }

  return (
    <iframe
      title="viewer"
      frameBorder={0}
      width={width}
      height={height}
      style={{
        ...style,
        width,
        height,
      }}
      src={newSrc}
      {...rest}
    />
  );
};

Index.displayName = 'SimpleViewer';
export default Index;
